/*
 * @Description: 新建单位弹窗
 * @Author: Rfan
 * @Date: 2022-01-07 14:54:11
 * @LastEditTime: 2022-05-26 17:18:23
 */

import { useEffect, useState } from 'react';
import { Divider, Form, Input, Radio, Select } from 'antd';
import { useNavigate } from 'react-router-dom';
import type { FC } from 'react';
import type { FormInstance } from 'antd';
import { useUnitContext } from '../../../contexts/UnitContext';

const { Option } = Select;

interface AddUnitFormProps {
  data?: any;
  jumpToFond?: boolean;
  form: FormInstance;
  visible: boolean;
  closeDialog: any;
}

const AddUnitForm: FC<AddUnitFormProps> = (props) => {
  const { data, jumpToFond, form, visible, closeDialog } = props;
  const { stateList, onAddUnit, onEditUnit, getUnitById } = useUnitContext();

  const navigate = useNavigate();

  // 是否编辑
  const [editFlag, setEditFlag] = useState(false);
  // 是否子单位
  const [subFlag, setSubFlag] = useState(false);
  // 单位编码使用系统分配 复选框选中状态
  // 0917 暂时取消默认选中
  const [autoCode, setAutoCode] = useState(false);

  useEffect(() => {
    if (visible) {
      if (data?.pid) {
        setSubFlag(true);
      }
      if (data?.id) {
        setEditFlag(true);
        form.setFieldsValue(data);
      } else {
        form.setFieldsValue({ isValid: 0 });
      }
    }
  }, [visible]);

  // // 单位编码使用系统分配 选中状态变化方法
  // const handleCodeChange = (evt: any) => {
  //   setAutoCode(evt.target.checked);
  // };

  // 新增单位方法
  const onFinish = async (values: any) => {
    if (editFlag) {
      values.id = data.id;
      onEditUnit(values).then(() => {
        submitSuccess();
      });
    } else {
      if (subFlag) {
        values.pid = data.pid;
      }
      const result = await onAddUnit(values);

      if (jumpToFond && result.id) {
        navigate(`../fonds?unitId=${result.id}`);
      }
      submitSuccess();
    }
  };

  /**
   * @description: 提交失败
   * @param {any} errorInfo 失败信息
   */
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const submitSuccess = () => {
    closeDialog();
  };

  return (
    <Form
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      preserve={false}
      form={form}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      {subFlag && (
        <>
          <Form.Item label="上级单位">{getUnitById(data.pid).unitName}</Form.Item>
          <Divider />
        </>
      )}
      <Form.Item
        name="unitName"
        label="单位名称"
        extra="注意：单位名称不能重复（限制10字）"
        rules={[{ required: true, message: '请填写单位名称' }]}
      >
        <Input showCount maxLength={10} />
      </Form.Item>

      {/* TODO: 恢复系统分配复选框后 删除外层 name 属性 */}
      <Form.Item label="单位编码" name="unitCode" extra="单位编码不能重复" required>
        {/* <Space> */}
        {/*  <Form.Item */}
        {/*    name="unitCode" */}
        {/*    noStyle */}
        {/*    rules={[{ required: true, message: '请填写单位编码' }]} */}
        {/*  > */}
        <Input disabled={autoCode} />
        {/* </Form.Item> */}
        {/* <Checkbox checked={autoCode} onClick={handleCodeChange}> */}
        {/*  使用系统分配 */}
        {/* </Checkbox> */}
        {/* </Space> */}
      </Form.Item>

      <Form.Item name="isValid" label="状态">
        <Select>
          {stateList.map((item: any) => (
            <Option value={item.id}>{item.name}</Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item name="remark" label="单位备注">
        <Input.TextArea placeholder="" showCount maxLength={2000} />
      </Form.Item>

      {subFlag && (
        <Form.Item label="上级巡查">
          <Radio.Group value={1}>
            <Radio value={1}>同意</Radio>
            <Radio value={2}>不同意</Radio>
          </Radio.Group>
        </Form.Item>
      )}
    </Form>
  );
};

export default AddUnitForm;
